import React, { useRef, useReducer, useEffect } from 'react'
import { Form, Modal, Radio, Space, Button, message } from 'antd'
import { reducer, initialState } from './reducer'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import moment from 'moment'
import { awaitWrap } from '@js/tool'
import { delServiceRequest, updateModalRequest, addModalRequest } from './ajax'
import { submitFiles } from '@js/request'
import _ from 'loadsh'
import EmsForm from '../Forms/EmsForm'
import NotarizationForm from '../Forms/NotarizationForm'
import DirectForm from '../Forms/DirectForm'
import SceneForm from '../Forms/SceneForm'
import ElectronicForm from '../Forms/ElectronicForm'
import NoticeForm from '../Forms/NoticeForm'
const { Item } = Form
const { confirm } = Modal
const longLabel = { span: 3 }
const longWrap = { span: 20 }
// const typeList = ['EMS', '公证送达', '直接送达', '现场送达']
const typeList = ['EMS', '公证送达', '直接送达', '现场送达', '电子送达', '公告送达']

// 改变送达类型
function changeToType (d, formRef, dispatch) {
  dispatch({ type: 'toType', data: d })
  const c = formRef.current
  // c.resetFields()
  c.setFieldsValue({
    to_type: d,
    status: '送达'
  })
}

// 处理完成操作
async function onFinish (d, caseDetail, theme, hide, refreshCurrentTableFn, dispatch) {
  d.islast_known_place = d.islast_known_place ? 1 : 0
  let requestFn = addModalRequest
  if (d.id) {
    requestFn = updateModalRequest
  }
  const h = message.loading('提交中', 120)
  const file = d.file ? d.file.fileList : []
  let fileid = ''
  if (file.length) {
    try {
      fileid = await submitFiles(file)
    } catch (e) {
      hide()
      return message.warning('上传图片失败')
    }
  }
  delete d.file
  d.caseid = caseDetail.id
  d.topicid = theme.key
  d.topic_name = theme.title
  d.fileid = fileid
  if (d.send_datetime instanceof moment) {
    d.send_datetime = Math.floor(d.send_datetime / 1000)
  }
  if (d.arrive_datetime instanceof moment) {
    d.arrive_datetime = Math.floor(d.arrive_datetime / 1000)
    if (d.status === undefined) {
      d.status = '送达'
    }
  }
  if (d.documentid && d.documentid instanceof Array) {
    d.documentid = d.documentid.join(',')
  }
  const [e] = await awaitWrap(requestFn(d))
  h()
  if (e) {
    return message.error(e.message)
  }
  hide()
  refreshCurrentTableFn()
  dispatch({ type: 'currentService', data: null })
  dispatch({ type: 'refreshCurrentTableFn', data: () => {} })
}

function Footer ({ data: d, hide, formRef, refreshCurrentTableFn }) {
  return (
    <Space>
      {d && d.id && !d.emscode ? <Button ghost danger onClick={() => delConfirm(d, hide, refreshCurrentTableFn)}>删除</Button> : null}
      <Button onClick={hide}>取消</Button>
      <Button type='primary' onClick={() => formRef.current.submit()}>确定</Button>
    </Space>
  )
}

// 删除二次提示
function delConfirm ({ contract, id }, hide, refreshCurrentTableFn) {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: '您确定要删除本送达吗？',
    onOk: () => {
      delHandle(id, hide, refreshCurrentTableFn)
    }
  })
}

// 删除操作
async function delHandle (id, hide, refreshCurrentTableFn) {
  const h = message.loading('删除中', 120)
  const [e] = await awaitWrap(delServiceRequest(id))
  h()
  if (e) {
    return message.error(e.message)
  }
  hide()
  refreshCurrentTableFn()
}

// 更新state
function initState (pState, dispatch, caseDetail, common, theme) {
  const keys = ['dictionaries', 'staffs', 'notaries', 'arbitrators', 'refreshCurrentTableFn', 'addressList', 'electronicAddressList']
  keys.forEach(k => {
    dispatch({ type: k, data: pState[k] })
  })
  dispatch({ type: 'caseDetail', data: caseDetail })
  dispatch({ type: 'common', data: common })
  dispatch({ type: 'theme', data: theme })
}

// 初始化文书
async function initFiles (caseid, common, dispatch) {
  const [e, d] = await awaitWrap(common.$getFileList(caseid))
  if (e) {
    return message.error(e.message)
  }
  dispatch({ type: 'files', data: d._fileList })
}

// 初始化数据
function initDefaultData (formRef, itemRef, data, caseDetail, dispatch) {
  const c = formRef.current
  const d = _.cloneDeep(data)
  if (!c) {
    return setTimeout(() => {
      initDefaultData(formRef, itemRef, data, caseDetail, dispatch)
    }, 100)
  }
  if (d && d.action_subject && itemRef.current) {
    itemRef.current.changeSubject(d.action_subject, formRef, caseDetail, d, dispatch)
  }
  if (d.id) {
    if (d.send_datetime) {
      d.send_datetime = moment(d.send_datetime * 1000)
    } else {
      d.send_datetime = undefined
    }
    if (d.arrive_datetime) {
      d.arrive_datetime = moment(d.arrive_datetime * 1000)
    } else {
      d.arrive_datetime = undefined
    }
  }
  if (d.documentid) {
    d.documentid = d.documentid.split(',').map(li => li.trim())
  } else {
    d.documentid = undefined
  }
  d.islast_known_place = d.islast_known_place === 1
  dispatch({ type: 'toType', data: d.to_type })
  c.setFieldsValue(d)
}

function Main ({ data = {}, theme, visible, hide, dictionaries, caseDetail, common, refreshCurrentTableFn, pState, pDispatch }) {
  const formRef = useRef(null)
  const itemRef = useRef(null)
  const [state, dispatch] = useReducer(reducer, initialState)
  useEffect(() => {
    initState(pState, dispatch, caseDetail, common, theme)
  }, [caseDetail, common, pState, theme])
  useEffect(() => {
    if (visible && data) {
      initDefaultData(formRef, itemRef, data, caseDetail, dispatch)
    }
  }, [visible, caseDetail, data])
  useEffect(() => {
    if (!visible) {
      dispatch({ type: 'reset' })
    }
  }, [visible])
  useEffect(() => {
    if (common) {
      initFiles(caseDetail.id, common, dispatch)
    }
  }, [caseDetail.id, common])
  return (
    <Modal
      title={data && data.id ? '修改送达' : '新增送达'}
      open={visible}
      width={800}
      onCancel={hide}
      footer={<Footer data={data} hide={hide} formRef={formRef} refreshCurrentTableFn={refreshCurrentTableFn} />}
      maskClosable={false}
      destroyOnClose
    >
      <Form name='add-service' labelCol={longLabel} wrapperCol={longWrap} ref={formRef} onFinish={d => onFinish(d, caseDetail, theme, hide, refreshCurrentTableFn, pDispatch)}>
        <Item name='to_type' label='送达方式' rules={[{ required: true, message: '送达方式不能为空' }]}>
          <Radio.Group onChange={e => changeToType(e.target.value, formRef, dispatch)}>
            {typeList.map(li => {
              return (<Radio.Button key={li} value={li}>{li}</Radio.Button>)
            })}
          </Radio.Group>
        </Item>
        {state.toType === 'EMS' && <EmsForm ref={itemRef} pState={state} pDispatch={dispatch} formRef={formRef} />}
        {state.toType === '公证送达' && <NotarizationForm ref={itemRef} pState={state} pDispatch={dispatch} formRef={formRef} />}
        {state.toType === '直接送达' && <DirectForm ref={itemRef} pState={state} pDispatch={dispatch} formRef={formRef} />}
        {state.toType === '现场送达' && <SceneForm ref={itemRef} pState={state} pDispatch={dispatch} formRef={formRef} />}
        {state.toType === '电子送达' && <ElectronicForm ref={itemRef} pState={state} pDispatch={dispatch} formRef={formRef} />}
        {state.toType === '公告送达' && <NoticeForm ref={itemRef} pState={state} pDispatch={dispatch} formRef={formRef} />}
      </Form>
    </Modal>
  )
}

export default Main
